﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.Common.C_Enum;
using STHPMS1.ICore.I_Entity.Stmpms1;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using STHPMS1.Common.C_Extension;
using System.Collections;
using System.Text;
using System.IO;

namespace STHPMS1.Web.W_Controller.Decision.Repair
{
    [RoutePrefix("api/repair")]
    public class RepairController : STHPMS1.Web.W_Core.MyController
    {
        /// <summary>
        /// 获取需要大中修的路段信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [Route("seg")]
        [Route("seg/page/{page?}", Name = "GetRepairByPage")]
        [Route("seg/rows/{rows?}")]
        [Route("seg/page/{page?}/rows/{rows?}")]
        public IHttpActionResult GetSegList(int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p > 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;

            Expression<Func<Dn_Divi_Result, bool>> exp = pre => (pre.Segid_Main == (int)MainTypeEnum.Middle || pre.Segid_Main == (int)MainTypeEnum.Overhaul);

            var data = this.Scene.Bll.Dn_Divi_Result.Get<Dn_Divi_Result>(exp, info).ToArray();
            if (data == null) return NotFound();
            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }
        /// <summary>
        /// 获取初选方案信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [Route("plan0")]
        [Route("plan0/page/{page?}", Name = "GetPlan0ByPage")]
        [Route("plan0/rows/{rows?}")]
        [Route("plan0/page/{page?}/rows/{rows?}")]
        public IHttpActionResult GetPlan0List(int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p > 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;
            
            var data = this.Scene.Bll.Dr_Largemeas_Ini.Get<Dr_Largemeas_Ini>(null, info).ToArray();
            if (data == null) return NotFound();
            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }
        /// <summary>
        /// 保存初选方案
        /// </summary>
        /// <param name="entity"></param>

        [Route("add")]
        public void PostAdd(Dr_Largemeas_Ini entity)
        {
            this.Scene.Bll.Dr_Largemeas_Ini.Save(entity);
        }
        /// <summary>
        /// 删除初选方案
        /// </summary>
        /// <param name="entity"></param>
        [Route("del0")]
        public void Delete0(Dr_Largemeas_Ini entity)
        {
            this.Scene.Bll.Dr_Largemeas_Ini.Remove(entity);
        }
        /// <summary>
        ///  根据路段Id与材料类型，获取铣刨面层的工艺厚度
        /// </summary>
        /// <param name="mainSegId"></param>
        /// <param name="materialType"></param>
        /// <returns></returns>
        [Route("t_get")]
        public double GetMillingThinkness(string mainSegId, int materialType)
        {
            return this.Scene.Bll.Dr_Largemeas_Ini.GetMillingThinkness(mainSegId, materialType);
        }
        /// <summary>
        /// 保存厚度设计信息
        /// </summary>
        /// <returns></returns>
        [Route("t_save")]
        public HttpResponseMessage PostSaveThinkness()
        {
            string iniproj_Id = HttpContext.Current.Request.Form["Iniproj_Id"];
            string medi_Maintype = HttpContext.Current.Request.Form["Medi_Maintype"];
            string stru_Combi = HttpContext.Current.Request.Form["Stru_Combi"];

            if (string.IsNullOrEmpty(iniproj_Id)) throw new Exception("初选方案不能为空!");
            if (string.IsNullOrEmpty(medi_Maintype)) throw new Exception("大中修类型不能为空!");
            if (string.IsNullOrEmpty(stru_Combi)) throw new Exception("结构组合不能为空!");

            string[] combiArray = stru_Combi.Split(',');
            Dictionary<int, double> dict = new Dictionary<int, double>();
            foreach (var combi in combiArray)
            {
                string key = "M" + combi;
                string value = HttpContext.Current.Request.Form[key];
                if (string.IsNullOrEmpty(value)) value = "0";
                dict.Add(int.Parse(combi), double.Parse(value));
            }
            this.Scene.Bll.Dr_Ini_Stru.SaveThinkness(iniproj_Id, int.Parse(medi_Maintype), dict);

            var response = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GetRepairByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        /// <summary>
        /// 获取初选结构组合信息
        /// </summary>
        /// <param name="iniproj_Id"></param>
        /// <returns></returns>
        [Route("t_combi")]
        public dynamic GetThinknessByPlan(string iniproj_Id)
        {
            return this.Scene.Bll.Dr_Ini_Stru.Get<Dr_Ini_Stru>(p => p.Iniproj_Id == iniproj_Id, null);
        }
        /// <summary>
        /// 获取初选方案信息
        /// </summary>
        /// <param name="iniproj_Id"></param>
        /// <returns></returns>
        [Route("m_get")]
        public dynamic GetMaterialByPlan(string iniproj_Id)
        {
            var plan = this.Scene.Bll.Dr_Largemeas_Ini.Get<Dr_Largemeas_Ini>(p => p.Iniproj_Id == iniproj_Id, null).FirstOrDefault();
            return plan;
        }
        /// <summary>
        /// 根据组合结构获取材料类别对应的层次及材料
        /// </summary>
        /// <param name="combi"></param>
        /// <param name="iniproj_Id"></param>
        /// <returns></returns>
        [Route("c_get")]
        public dynamic GetMaterialByCombi(string combi, string iniproj_Id)
        {
            var material = this.Scene.Bll.Dr_Stru_Mate.GetMaterialByType<Dr_Stru_Mate>(combi);

            dynamic mate = new ArrayList();
            Dr_Stru_Mate lastItem = null;

            int s_index = -1;//结构索引
            int l_index = 0;//层索引
            int m_index = 0;//材料索引


            foreach (var item in material)
	        {
                if (lastItem != null && lastItem.Stru_Type == item.Stru_Type)
                {
                    m_index++;
                    if (lastItem.Layer_Dictid != item.Layer_Dictid)
                    {
                        l_index++;
                        m_index = 0;

                        mate[s_index].LayList.Add(new ExpandoObject());
                        mate[s_index].LayList[l_index].Layer_Dictid = item.Layer_Dictid;
                        mate[s_index].LayList[l_index].Layer_Name = ((RepairLayerEnum)item.Layer_Dictid).GetEnumDescription();
                        mate[s_index].LayList[l_index].MaterialList = new ArrayList();
                    }

                    mate[s_index].LayList[l_index].MaterialList.Add(new ExpandoObject());
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Id = item.Stru_Id;
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Name = item.Stru_Name;
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Price = item.Stru_Price;
                }
                else
                {
                    s_index++;
                    l_index = 0;
                    m_index = 0;

                    mate.Add(new ExpandoObject());
                    mate[s_index].Stru_Type = item.Stru_Type;
                    mate[s_index].Stru_TypeText = ((MaterialTypeEnum)item.Stru_Type).GetEnumDescription();
                    mate[s_index].LayList = new ArrayList();

                    mate[s_index].LayList.Add(new ExpandoObject());
                    mate[s_index].LayList[l_index].Layer_Dictid = item.Layer_Dictid;
                    mate[s_index].LayList[l_index].Layer_Name = ((RepairLayerEnum)item.Layer_Dictid).GetEnumDescription();
                    mate[s_index].LayList[l_index].MaterialList = new ArrayList();

                    mate[s_index].LayList[l_index].MaterialList.Add(new ExpandoObject());
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Id = item.Stru_Id;
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Name = item.Stru_Name;
                    mate[s_index].LayList[l_index].MaterialList[m_index].Stru_Price = item.Stru_Price;
                }

                lastItem = item;
	        }


            s_index = 0;
            var laymate = this.Scene.Bll.Dr_Ini_Stru.Get<Dr_Ini_Laymate>(p => p.Iniproj_Id == iniproj_Id, null);
            dynamic lay = new ArrayList();
            foreach (var item in laymate)
            {
                Dr_Stru_Mate stru = material.FirstOrDefault(p => p.Stru_Id == item.Stru_Id);
                if (stru == null) continue;

                lay.Add(new ExpandoObject());
                lay[s_index].id = "M" + stru.Stru_Type + "_L" + stru.Layer_Dictid;
                lay[s_index].val = item.Mater_Thick;
                lay[s_index].stru_id = item.Stru_Id;
                s_index++;
            }


            List<string> ids = new List<string>();
            StringBuilder sb = new StringBuilder();
            foreach (var material1 in mate)
            {
                for (var i = 0; i < material1.LayList.Count; i++)
                {

                    var lay1 = material1.LayList[i];
                    var name = "M" + material1.Stru_Type + "_L" + lay1.Layer_Dictid;
                    ids.Add(name);

                    StringBuilder opt = new StringBuilder();
                    for (int j = 0; j < lay1.MaterialList.Count; j++)
                    {
                        opt.AppendFormat("<option value='{0}'>{1}</option>", lay1.MaterialList[j].Stru_Id, lay1.MaterialList[j].Stru_Name);
                    }


                    string td0 = "";
                    if(i==0)
                        td0=string.Format("<td class='thin' rowspan='{1}' >{0}</td> ", material1.Stru_TypeText, material1.LayList.Count);
                    string td2Value="";
                    string td3Value="";
                    dynamic layItem = null;
                    foreach (dynamic item in lay)
                    {
                        if(item.id==name)
                        {
                            layItem = item;
                            break;
                        }
                    }
                    if (layItem != null)
                    {
                        td2Value = string.Format(",value:'{0}'", layItem.stru_id);
                        td3Value = string.Format(",value:{0}", layItem.val);
                    }

                    string td1 = string.Format("<td class='thin'>{0}</td> ", lay1.Layer_Name);
                    string td2 = string.Format("<td class='thin' ><select class='easyui-combobox' name='{0}' id='{0}' style='width:170px;'  data-options=\" prompt:'材料类型',valueField:'Stru_Id',textField:'Stru_Name' {2} \">{1}</select></td> ", name, opt.ToString(), td2Value);
                    string td3 = string.Format("<td class='thin'>厚度 cm <input name='{0}' id='{0}' class='easyui-numberbox' style='width: 160px; height: 20px;' data-options=\" min:0,precision:2  {1} \"/></td> ", name + "_val", td3Value);

                    sb.AppendFormat("<tr>{0}{1}{2}{3}</tr>", td0, td1, td2, td3);
                }
            }

            dynamic data = new ExpandoObject();
            data.mate = mate;
            //data.lay = lay;
            data.mate_combi = string.Join<string>(",", ids);
            data.tr = sb.ToString();


            
            return data;
        }


        /// <summary>
        /// 保存初选方案选择的材料及厚度
        /// </summary>
        /// <returns></returns>
        [Route("m_save")]
        public HttpResponseMessage PostSaveMaterial()
        {
            string iniproj_Id = HttpContext.Current.Request.Form["Iniproj_Id"];
            string hotmonth = HttpContext.Current.Request.Form["Hotmonth"];
            string exetem = HttpContext.Current.Request.Form["Exetem"];
            string annurain = HttpContext.Current.Request.Form["Annurain"];
            string mate_Combi = HttpContext.Current.Request.Form["Mate_Combi"];

            if (string.IsNullOrEmpty(iniproj_Id)) throw new Exception("初选方案不能为空!");

            string[] combiArray = mate_Combi.Split(',');
            List<Dr_Ini_Laymate> laymateList=new List<Dr_Ini_Laymate>();
            foreach (var combi in combiArray)
            {
                Dr_Ini_Laymate mate=new Dr_Ini_Laymate();
                string[] lays=combi.Split('_');

                mate.Iniproj_Id=iniproj_Id;
                mate.Inistru_Id=iniproj_Id+"_"+lays[0].Replace("M","");               
                mate.Layer_Dictid=Convert.ToInt32(lays[1].Replace("L",""));

                mate.Stru_Id= HttpContext.Current.Request.Form[combi];
                if (string.IsNullOrEmpty(mate.Stru_Id)) continue;
                string thick = HttpContext.Current.Request.Form[combi + "_val"];
                if (string.IsNullOrEmpty(thick)) continue;
                mate.Mater_Thick =Convert.ToDouble(thick);
                laymateList.Add(mate);
            }

            this.Scene.Bll.Dr_Ini_Stru.SaveMaterials<Dr_Ini_Laymate>(iniproj_Id,
                hotmonth,
                exetem,
                annurain,
                laymateList);

            var response = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GetRepairByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        /// <summary>
        /// 获取需要比选的大中修的路段信息
        /// </summary>
        /// <returns></returns>
        [Route("s_get")]
        public dynamic GetMainSeg()
        {
            var segList = this.Scene.Bll.Dr_Largemeas_Ini.GetMainSeg();
            var data=from p in segList
                     select new { id =p };
            return data;
        }
        /// <summary>
        /// 获取路段的比选方案信息
        /// </summary>
        /// <returns></returns>

        [Route("b_get")]
        public dynamic GetPlan(string mainSegId)
        {
            dynamic data = new ArrayList();
            var mateList=this.Scene.Bll.Dr_Stru_Mate.Get<Dr_Stru_Mate>(null, null);

            foreach (var proj in this.Scene.Bll.Dr_Largemeas_Ini.Get<Dr_Largemeas_Ini>(p => p.Mainsegid == mainSegId, null))
	        {
                var layList = this.Scene.Bll.Dr_Ini_Stru.Get<Dr_Ini_Laymate>(p => p.Iniproj_Id == proj.Iniproj_Id, null);

                foreach (var item in layList)
                {
                    var m = mateList.FirstOrDefault(p=>p.Stru_Id==item.Stru_Id);
                    if (m == null) continue;

                    dynamic mate = new ExpandoObject();
                    mate.iniproj_Id = proj.Iniproj_Id;
                    mate.iniproj_Name = proj.Meas_Name;
                    mate.stru_Type = ((MaterialTypeEnum)m.Stru_Type).GetEnumDescription();
                    mate.stru_Name = m.Stru_Name;
                    mate.stru_Thinkness = item.Mater_Thick;

                    data.Add(mate);
                }
	        }
            
            return data;
        }


        /// <summary>
        /// 保存比选方案
        /// </summary>
        /// <returns></returns>
        [Route("b_save")]
        public void PostPlan()
        {
            string schmeName = HttpContext.Current.Request.Form["schmeName"];
            string mainSegId = HttpContext.Current.Request.Form["mainSegId"];
            string ids = HttpContext.Current.Request.Form["ids"];

            if (string.IsNullOrEmpty(schmeName)) throw new Exception("大中修比选方案名称不能为空!");
            if (string.IsNullOrEmpty(mainSegId)) throw new Exception("进行大中修比选路段不能为空!");
            if (string.IsNullOrEmpty(ids)) throw new Exception("大中修比选的初选方案不能为空!");

            this.Scene.Bll.Dr_Decision_Tree.SavePlan(schmeName,mainSegId,ids.Split(','));
        }
    }
}